import { Component, OnInit, Input, Inject, forwardRef } from '@angular/core';
import { AlertController } from '@ionic/angular';
import { AppGlobalService } from '../../shared/service/app-global.service';
import { HttpService } from '../../shared/service/http.service';
import { isArray, isBoolean, isNumber } from 'util';
import { connect } from 'tls';
import { EventService } from '../../shared/service/event.service';
// import { TabsService } from 'src/app/shared/service/tabs.service';

import { FormGroup, FormControl, Validators, ValidatorFn, AbstractControl } from '@angular/forms';
@Component({
    selector: 'app-sign-offer',
    templateUrl: './sign-offer.component.html',
    styleUrls: ['./sign-offer.component.scss'],
})
export class SignOfferComponent implements OnInit {
    @Input() tagData: any;
    formGroup: FormGroup = new FormGroup({});
    listdata: any;
    iftrue: boolean;
    appEditItem: any;
    tagDatas: any;
    ifadvertis: any; // 是否广告参数
    ifprepay: any; // 是否预付
    ifserveday: any; // 是否展示服务
    ifpicker: any; // 是否禁用具体位置
    advertisementlist: any; // 广告位数组
    advertisementlist2: any; // 广告位数组
    advertisementlist3: any; // 广告位数组
    sessionId: string;
    cycletext: any;
    areas: any;
    Status: any;
    constructor(
        private alert: AlertController,
        private appGlobalService: AppGlobalService,
        private http: HttpService,
        private eventService: EventService
    ) { }

    ngOnInit() {
        this.sessionId = localStorage.getItem('sessionId');
        this.tagData.data.advertisement.value = "text";
        this.Status = false;
        this.tagDatas = this.tagData.data;
        this.advertisementlist = this.tagDatas.advertisement.data;
        this.advertisementlist2 = JSON.stringify(this.tagDatas.advertisement.data);
        this.advertisementlist.forEach(element => {
            element.children.forEach(e => {
                if (e.children.length !== 0) {
                    e.children = "";
                }
            });
        });
        this.iftrue = false;
        this.ifadvertis = true;
        this.ifprepay = false;
        this.ifpicker = true;
        this.choosetimelimit(1);
    }
    async cancel() {
        let tip = "确定放弃本次发布？";
        if (this.tagDatas.title.indexOf('修改') !== -1) {
            tip = "是否放弃本次编辑？";
        }
        const alert = await this.alert.create({
            message: tip,
            buttons: [
                {
                    text: '取消',
                    role: 'cancel',
                    cssClass: 'secondary',
                    handler: () => {
                    }
                }, {
                    text: '确定',
                    cssClass: 'LJ',
                    handler: () => {
                        this.appGlobalService.goBack();
                        this.appGlobalService.popTarget();
                    }
                }
            ]
        });
        await alert.present();
    }
    choosetimelimit(e) {
        this.tagDatas.advertisement.textInputWithEndLabel.rules[0].value = "";
        if (e === 1) {
            this.tagDatas.cycle.forEach(element => {
                if (element.isCheck === "true") {
                    this.cycletext = element;
                    if (element.cycleFlag && element.isCheck === "true") {
                        this.ifserveday = true;
                    } else {
                    }
                }

            });
        } else {
            this.tagDatas.cycle.forEach(element => {
                if (element.name === e.name) {
                    element.isCheck = "true";
                    this.cycletext = element;
                    if (element.cycleFlag) {
                        this.ifserveday = true;
                        this.cycletext = element;
                    } else {
                        this.ifserveday = false;
                    }
                } else {
                    element.isCheck = "false";
                }
            });
        }
    }
    /* 选择广告位 */
    onOk2(result, type) {
        if (type === 1) {
            this.tagDatas.advertisement.placeHolder = result[0].label + result[1].label;
            JSON.parse(this.advertisementlist2).forEach(element => {
                element.children.forEach(e => {
                    if (e.code === result[1].code) {
                        this.advertisementlist3 = e.children;
                        this.ifpicker = false;
                        this.tagDatas.advertisement.subPlaceHolder = "具体位置";
                    }
                });
            });
        } else {
            this.tagDatas.advertisement.subPlaceHolder = result[0].label;
            if (this.tagDatas.advertisement.value) {
                this.tagDatas.advertisement.value = result[0].code;
            }
        }
    }
    tijiao() {
    }
    upDatePepper() {
    }
    // 刷新
    offerrefresh() {
        // content值
        const contents = this.tagDatas.price.button.submit.content;
        // 提交id值
        const listid = this.tagDatas.price.button.submit.id;
        // 广告值
        // tslint:disable-next-line: variable-name
        const quote_ad_position = this.tagDatas.advertisement.formKey;
        // tslint:disable-next-line: variable-name
        const quote_ad_position_value = this.tagDatas.advertisement.value;
        // 服务天数的值
        const quotePrepayPrice = this.tagDatas.advertisement.textInputWithEndLabel.formKey;
        const day = this.tagDatas.advertisement.textInputWithEndLabel.rules[0].value;
        // 选择的服务月份的值
        // tslint:disable-next-line: variable-name
        const service_mode = this.cycletext.data[0].formKey;
        // tslint:disable-next-line: variable-name
        const service_modevalue = this.cycletext.data[0].value;
        // tslint:disable-next-line: variable-name
        let quote_service_days;
        // tslint:disable-next-line: variable-name
        let quote_service_daysvalue;
        if (this.cycletext.data.length > 1) {
            quote_service_days = this.cycletext.data[1].formKey;
            quote_service_daysvalue = this.cycletext.data[1].value;
        } else {
            quote_service_days = this.tagDatas.cycleForm.formKey;
            quote_service_daysvalue = this.tagDatas.cycleForm.rules[0].value;
            // tslint:disable-next-line: radix
            if (parseInt(quote_service_daysvalue) < 0 || parseInt(quote_service_daysvalue) > 180) {
                this.appGlobalService.showToast(this.tagDatas.cycleForm.rules[1].message, 500, 'top');
                return;
            }
        }
        let daynum; daynum = quote_service_daysvalue;
        /* let servicedata=JSON.parse('{'+'"'+quote_service_days+'"'+":"+'"'+quote_service_daysvalue+'"'+'}'); */
        let servicedata; servicedata = { [quote_service_days]: quote_service_daysvalue };
        // 是否需要广告位广告位的值
        let ifadvertising;
        if (this.ifadvertis === true) {
            ifadvertising = {
                [quote_ad_position]: quote_ad_position_value,
                [quotePrepayPrice]: day,
                [service_mode]: service_modevalue,
            };
        } else {
            ifadvertising = {
                [service_mode]: service_modevalue
            };
        }
        // 相关验证
        if (this.verificationday(quote_service_daysvalue) === false) {
            // tslint:disable-next-line: max-line-length
            if (quote_service_daysvalue === "" || quote_service_daysvalue === undefined || quote_service_daysvalue === "true" || quote_service_daysvalue === null) {
                this.appGlobalService.showToast(this.tagDatas.cycleForm.rules[0].message, 500, 'top');
                return;
            } else {
                this.appGlobalService.showToast(this.tagDatas.cycleForm.rules[1].message, 500, 'top');
                return;
            }
        } else {
        }
        if (this.tagDatas.advertisement.value === "text" && this.ifadvertis === true) {
            this.appGlobalService.showToast('请选择广告位', 500, 'top');
            return;
        }
        if (this.verificationday1(day) === false) {
            // tslint:disable-next-line: max-line-length
            if ((day === "" && this.ifadvertis === true) || (day === "true" && this.ifadvertis === true) || (day === null && this.ifadvertis === true)) {
                this.appGlobalService.showToast(this.tagDatas.advertisement.textInputWithEndLabel.rules[0].message, 500, 'top');
                return;
            } else {
                this.appGlobalService.showToast(this.tagDatas.advertisement.textInputWithEndLabel.rules[1].message, 500, 'top');
                return;
            }
        } else {
            // tslint:disable-next-line: radix
            if (parseInt(day) < 0 || parseInt(day) > parseInt(daynum)) {
                this.appGlobalService.showToast("请填写正确的服务天数，1-" + daynum + "天之间", 500, 'top');
                return;
            }
        }
        // 要传后台的参数
        let contentsitem; contentsitem = JSON.stringify(contents);
        let content; content = Object.assign(
            JSON.parse(contentsitem),
            ifadvertising,
            servicedata
        );
        const params = {
            content,
            id: listid,
            sessionId: this.sessionId
        };
        // 请求获取新数据
        this.http.post('application/submit', params, res => {
            // 请求数据成功
            if (res.success && res.data) {
                // 筛选数据
                this.tagDatas.price.value = res.data.eventResult;
                this.appGlobalService.showToast(res.message, 2000, 'top');
            } else {
                // 请求数据失败
                this.appGlobalService.showToast(res.message, 2000, 'middle');
            }
        });
    }
    /* 是否预付 */
    changeadvertisement() {
        this.ifprepay = !this.ifprepay;
    }
    /* 提交 */
    offersubmit() {
        // content 值
        const contents = this.tagDatas.button.submit.content;
        // 提交id值
        const listid = this.tagDatas.button.submit.id;
        // 广告值
        // tslint:disable-next-line: variable-name
        const quote_ad_position = this.tagDatas.advertisement.formKey;
        // tslint:disable-next-line: variable-name
        const quote_ad_position_value = this.tagDatas.advertisement.value;
        // 广告天数的值
        const quotePrepayPrice = this.tagDatas.advertisement.textInputWithEndLabel.formKey;
        const day = this.tagDatas.advertisement.textInputWithEndLabel.rules[0].value;
        // 选择的服务月份的值
        // tslint:disable-next-line: variable-name
        const service_mode = this.cycletext.data[0].formKey;
        // tslint:disable-next-line: variable-name
        const service_modevalue = this.cycletext.data[0].value;
        // tslint:disable-next-line: variable-name
        let quote_service_days: string;
        // tslint:disable-next-line: variable-name
        let quote_service_daysvalue: string;
        if (this.cycletext.data.length > 1) {
            quote_service_days = this.cycletext.data[1].formKey;
            quote_service_daysvalue = this.cycletext.data[1].value;
        } else {
            quote_service_days = this.tagDatas.cycleForm.formKey;
            quote_service_daysvalue = this.tagDatas.cycleForm.rules[0].value;
            // tslint:disable-next-line: radix
            if (parseInt(quote_service_daysvalue) < 0 || parseInt(quote_service_daysvalue) > 180) {
                this.appGlobalService.showToast(this.tagDatas.cycleForm.rules[1].message, 500, 'top');
                return;
            }
        }
        let daynum; daynum = quote_service_daysvalue;
        /*  const servicedata = JSON.parse('{' + '"' + quote_service_days + '"' + ":" + '"' + quote_service_daysvalue + '"' + '}'); */
        let servicedata; servicedata = { [quote_service_days]: quote_service_daysvalue };
        // 报价的值
        // tslint:disable-next-line: variable-name
        const quote_price = this.tagDatas.price.formKey;
        // tslint:disable-next-line: variable-name
        const quote_pricevalue = this.tagDatas.price.value;
        // 优惠金额
        const discountsPrice = this.tagDatas.textInputWithEndLabel.formKey;
        const discountsPricevalue = this.tagDatas.textInputWithEndLabel.rules[0].value;
        // 预付金额
        const paymentPrice = this.tagDatas.PrepayPrice.textInputWithEndLabel.formKey;
        const paymentPricevalue = this.tagDatas.PrepayPrice.textInputWithEndLabel.rules[0].value;
        // 是否需要广告位广告位的值
        let ifadvertising;
        if (this.ifadvertis === true) {
            ifadvertising = {
                [quote_ad_position]: quote_ad_position_value,
                [quotePrepayPrice]: day,
                [service_mode]: service_modevalue,
                [quote_price]: quote_pricevalue
            };
        } else {
            ifadvertising = {
                [service_mode]: service_modevalue,
                [quote_price]: quote_pricevalue
            };
        }
        // 是否需要预付金额
        let ifpayment;
        if (this.ifprepay === true) {
            ifpayment = {
                [discountsPrice]: discountsPricevalue,
                [paymentPrice]: paymentPricevalue
            };
        } else {
            ifpayment = {
                [discountsPrice]: discountsPricevalue,
            };
            /*  ifpayment = JSON.parse('{' + '"' + discountsPrice + '"' + ":" + '"' + discountsPricevalue + '"' + '}'); */
        }
        // 相关验证
        if (this.verificationday(quote_service_daysvalue) === false) {
            // tslint:disable-next-line: max-line-length
            if (quote_service_daysvalue === "" || quote_service_daysvalue === undefined || quote_service_daysvalue === "true" || quote_service_daysvalue === null) {
                this.appGlobalService.showToast(this.tagDatas.cycleForm.rules[0].message, 500, 'top');
                return;
            } else {
                this.appGlobalService.showToast(this.tagDatas.cycleForm.rules[1].message, 500, 'top');
                return;
            }
        } else {
        }
        if (this.tagDatas.advertisement.value === "text" && this.ifadvertis === true) {
            this.appGlobalService.showToast('请选择广告位', 500, 'top');
            return;
        }
        if (this.verificationday1(day) === false) {
            // tslint:disable-next-line: max-line-length
            if ((day === "" && this.ifadvertis === true) || (day === "true" && this.ifadvertis === true) || (day == null && this.ifadvertis === true)) {
                this.appGlobalService.showToast(this.tagDatas.advertisement.textInputWithEndLabel.rules[0].message, 500, 'top');
                return;
            } else {
                this.appGlobalService.showToast(this.tagDatas.advertisement.textInputWithEndLabel.rules[1].message, 500, 'top');
                return;
            }
        } else {
            // tslint:disable-next-line: radix
            if (parseInt(day) < 0 || parseInt(day) > parseInt(daynum)) {
                this.appGlobalService.showToast("请填写正确的服务天数，1-" + daynum + "天之间", 500, 'top');
                return;
            }
        }
        if (this.verificationmoney(discountsPricevalue) === false) {
            console.log(this.verificationmoney(discountsPricevalue));
            if (discountsPricevalue === "" || discountsPricevalue === undefined || discountsPricevalue === "true") {
                this.appGlobalService.showToast(this.tagDatas.textInputWithEndLabel.rules[0].message, 500, 'top');
                return;
            } else {
                this.appGlobalService.showToast(this.tagDatas.textInputWithEndLabel.rules[1].message, 500, 'top');
                return;
            }
        } else {
            if (parseFloat(discountsPricevalue) < 500) {
                this.appGlobalService.showToast('优惠金额不能小于500', 500, 'top');
                return;
            }
        }
        if (this.verificationmoney1(paymentPricevalue) === false) {
            console.log(this.verificationmoney(discountsPricevalue));
            // tslint:disable-next-line: max-line-length
            if ((paymentPricevalue === "" && this.ifprepay === true) || (paymentPricevalue === "true" && this.ifprepay === true) || (paymentPricevalue == null && this.ifprepay === true)) {
                this.appGlobalService.showToast(this.tagDatas.PrepayPrice.textInputWithEndLabel.rules[0].message, 500, 'top');
                return;
            } else {
                this.appGlobalService.showToast(this.tagDatas.PrepayPrice.textInputWithEndLabel.rules[1].message, 500, 'top');
                return;
            }
        } else {
            console.log(parseFloat(discountsPricevalue));
            if (parseFloat(discountsPricevalue) < parseFloat(paymentPricevalue)) {
                this.appGlobalService.showToast('优惠金额不能小于预付金额', 500, 'top');
                return;
            }
        }

        const contentsitem = JSON.stringify(contents);
        const content = Object.assign(
            JSON.parse(contentsitem),
            ifadvertising,
            ifpayment,
            servicedata
        );
        const params = {
            content,
            id: listid,
            sessionId: this.sessionId
        };
        this.Status = true;
        // 请求获取新数据
        this.http.post('application/submit', params, res => {
            // 请求数据成功
            if (res.success && res.data) {
                // 筛选数据
                this.appGlobalService.showToast(res.message, 2000, 'top');
                // tslint:disable-next-line:no-shadowed-variable
                const params = {
                    pageId: this.tagDatas.button.submit.target,
                    params: contents,
                    sessionId: localStorage.getItem('sessionId')
                };
                const that = this;
                setTimeout(() => {
                    // localStorage.setItem("fromPostOrEdit", 'true');
                    this.appGlobalService.goBack();
                    this.appGlobalService.popTarget();
                    // 刷新
                    this.appGlobalService.reloadCurrentPage();
                }, 1000);
            } else {
                this.Status = false;
                // 请求数据失败
                this.appGlobalService.showToast(res.message, 2000, 'middle');
            }
        });
    }
    // 预览合同
    previewcontract() {
        // tslint:disable-next-line: variable-name
        const quote_ad_position = this.tagDatas.advertisement.formKey;
        // tslint:disable-next-line: variable-name
        const quote_ad_position_value = this.tagDatas.advertisement.value;
        // 广告天数的值
        const quotePrepayPrice = this.tagDatas.advertisement.textInputWithEndLabel.formKey;
        const day = this.tagDatas.advertisement.textInputWithEndLabel.rules[0].value;
        // 选择的服务月份的值
        // tslint:disable-next-line: variable-name
        const service_mode = this.cycletext.data[0].formKey;
        // tslint:disable-next-line: variable-name
        const service_modevalue = this.cycletext.data[0].value;
        // tslint:disable-next-line: variable-name
        let quote_service_days;
        // tslint:disable-next-line: variable-name
        let quote_service_daysvalue;
        if (this.cycletext.data.length > 1) {
            quote_service_days = this.cycletext.data[1].formKey;
            quote_service_daysvalue = this.cycletext.data[1].value;
        } else {
            quote_service_days = this.tagDatas.cycleForm.formKey;
            quote_service_daysvalue = this.tagDatas.cycleForm.rules[0].value;
            // tslint:disable-next-line: radix
            if (parseInt(quote_service_daysvalue) < 0 || parseInt(quote_service_daysvalue) > 180) {
                this.appGlobalService.showToast(this.tagDatas.cycleForm.rules[1].message, 500, 'top');
                return;
            }
        }
        const daynum = quote_service_daysvalue;
        /*   const servicedata = JSON.parse('{' + '"' + quote_service_days + '"' + ":" + '"' + quote_service_daysvalue + '"' + '}'); */
        const servicedata = { [quote_service_days]: quote_service_daysvalue };
        // 报价的值
        // tslint:disable-next-line: variable-name
        let quote_price; quote_price = this.tagDatas.price.formKey;
        // tslint:disable-next-line: variable-name
        let quote_pricevalue; quote_pricevalue = this.tagDatas.price.value;
        // 优惠金额
        const discountsPrice = this.tagDatas.textInputWithEndLabel.formKey;
        const discountsPricevalue = this.tagDatas.textInputWithEndLabel.rules[0].value;
        // 预付金额
        const paymentPrice = this.tagDatas.PrepayPrice.textInputWithEndLabel.formKey;
        const paymentPricevalue = this.tagDatas.PrepayPrice.textInputWithEndLabel.rules[0].value;
        // 是否需要广告位广告位的值
        let ifadvertising;
        if (this.ifadvertis === true) {
            ifadvertising = {
                [quote_ad_position]: quote_ad_position_value,
                [quotePrepayPrice]: day,
                [service_mode]: service_modevalue,
                [quote_price]: quote_pricevalue
            };
        } else {
            ifadvertising = {
                [service_mode]: service_modevalue,
                [quote_price]: quote_pricevalue
            };
        }
        // 是否需要预付金额
        let ifpayment;
        if (this.ifprepay === true) {
            ifpayment = {
                [discountsPrice]: discountsPricevalue,
                [paymentPrice]: paymentPricevalue
            };
        } else {
            ifpayment = {
                [discountsPrice]: discountsPricevalue,
            };
        }
        // 相关验证
        if (this.verificationday(quote_service_daysvalue) === false) {
            // tslint:disable-next-line: max-line-length
            if (quote_service_daysvalue === "" || quote_service_daysvalue === undefined || quote_service_daysvalue === "true" || quote_service_daysvalue === null) {
                this.appGlobalService.showToast(this.tagDatas.cycleForm.rules[0].message, 500, 'top');
                return;
            } else {
                this.appGlobalService.showToast(this.tagDatas.cycleForm.rules[1].message, 500, 'top');
                return;
            }
        } else {
        }
        if (this.tagDatas.advertisement.value === "text" && this.ifadvertis === true) {
            this.appGlobalService.showToast('请选择广告位', 500, 'top');
            return;
        }
        if (this.verificationday1(day) === false) {
            // tslint:disable-next-line: max-line-length
            if ((day === "" && this.ifadvertis === true) || (day === "true" && this.ifadvertis === true) || (day === null && this.ifadvertis === true)) {
                this.appGlobalService.showToast(this.tagDatas.advertisement.textInputWithEndLabel.rules[0].message, 500, 'top');
                return;
            } else {
                this.appGlobalService.showToast(this.tagDatas.advertisement.textInputWithEndLabel.rules[1].message, 500, 'top');
                return;
            }
        } else {
            // tslint:disable-next-line: radix
            if (parseInt(day) < 0 || parseInt(day) > parseInt(daynum)) {
                this.appGlobalService.showToast("请填写正确的服务天数，1-" + daynum + "天之间", 500, 'top');
                return;
            }
        }
        if (this.verificationmoney(discountsPricevalue) === false) {
            if (discountsPricevalue === "" || discountsPricevalue === undefined || discountsPricevalue === "true") {
                this.appGlobalService.showToast(this.tagDatas.textInputWithEndLabel.rules[0].message, 500, 'top');
                return;
            } else {
                this.appGlobalService.showToast(this.tagDatas.textInputWithEndLabel.rules[1].message, 500, 'top');
                return;
            }
        } else {
            if (parseFloat(discountsPricevalue) < 500) {
                this.appGlobalService.showToast('请填写正确的优惠金额，不能小于500', 500, 'top');
                return;
            }
        }
        if (this.verificationmoney1(paymentPricevalue) === false) {
            // tslint:disable-next-line: max-line-length
            if ((paymentPricevalue === "" && this.ifprepay === true) || (paymentPricevalue === "true" && this.ifprepay === true) || (paymentPricevalue === null && this.ifprepay === true)) {
                this.appGlobalService.showToast(this.tagDatas.PrepayPrice.textInputWithEndLabel.rules[0].message, 500, 'top');
                return;
            } else {
                this.appGlobalService.showToast(this.tagDatas.PrepayPrice.textInputWithEndLabel.rules[1].message, 500, 'top');
                return;
            }
        } else {
            if (parseFloat(discountsPricevalue) < parseFloat(paymentPricevalue)) {
                this.appGlobalService.showToast('优惠金额不能小于预付金额', 500, 'top');
                return;
            }
        }
        const content = Object.assign(
            ifadvertising,
            ifpayment,
            servicedata
        );
        const context = JSON.stringify(this.tagDatas.link.params);
        const contextdata = Object.assign(
            JSON.parse(context),
            content
        );
        const params = {
            pageId: this.tagDatas.link.target,
            params: contextdata,
            sessionId: localStorage.getItem('sessionId')
        };
        /* const paramsTEXT =JSON.stringify(params); */
        const that = this;
        if (this.tagDatas.link.type !== 'contract') {
            setTimeout(() => {
                // localStorage.setItem("fromPostOrEdit", 'true');
                localStorage.setItem('needRefresh', 'false');
                that.appGlobalService.goToForward(params);
            }, 1000);
        } else {
            localStorage.setItem('needRefresh', 'false');
            this.http.post('/element/serviceContract/url', params.params, res => {
                this.appGlobalService.openUrl(this.tagDatas.link.label, res.url, params.pageId, JSON.stringify(params.params));
            });
        }
    }
    verificationday(e) {
        const reg = /^[1-9]\d*$/;
        if (this.ifserveday === true) {
            return reg.test(e);
        } else {
            return true;
        }

    }
    verificationday1(e) {
        const reg = /^[1-9]\d*$/;
        if (this.ifadvertis === true) {
            return reg.test(e);
        } else {
            return true;
        }

    }
    verificationmoney(e) {
        const reg = /(?:^[-]?[1-9]\d{0,6}(?:$|(?:,\d{3})*(?:$|(\.\d{1,2}$))))|(?:(?:^[0](\.\d{1,2})?)|(?:^[-][0]\.\d{1,2}))$/;
        return reg.test(e);
    }
    verificationmoney1(e) {
        const reg = /(?:^[-]?[1-9]\d{0,6}(?:$|(?:,\d{3})*(?:$|(\.\d{1,2}$))))|(?:(?:^[0](\.\d{1,2})?)|(?:^[-][0]\.\d{1,2}))$/;
        if (this.ifprepay === true) {
            return reg.test(e);
        } else {
            return true;
        }
    }
    ifprepayclick() {
        this.ifprepay = !this.ifprepay;
    }
    ifadvertisclick() {
        this.ifadvertis = !this.ifadvertis;
    }
}
